# -*- coding;utf-8 -*-
"""
File name : Mypermission.PY
Program IDE : PyCharm
Create file time: 2022/3/30 16:07
File Create By Author : 朱清闯
"""
from rest_framework.permissions import BasePermission, IsAuthenticated, SAFE_METHODS
from django.core.cache import cache


class IsReadOnlyOrAdmin(BasePermission):
    def has_permission(self, request, view):
        return bool(
            # 如果是读请求，不校验用户，直接返回
            request.method in SAFE_METHODS or
            # 登录用户有所有权限，游客只读
            request.user and
            (request.user.is_superuser or request.user.is_staff)
        )


class IsOwnerPermission(BasePermission):
    def has_object_permission(self, request, view, obj):
        token = request.META.get("HTTP_TOKEN")
        token_user = cache.get(token)
        return obj.owner == token_user


class IsAdmin(BasePermission):
    def has_permission(self, request, view):
        return bool(request.user and request.user.is_staff or request.user.is_superuser)
